<meta charset="UTF-8">

<?php
include_once("functions/db_manipulate.php");
if (!init()) {
    redirect('login.php');
}

$link_id = connectDB();

startTransaction();

$timeStamp = getLocalTimeStamp();

$msgInsertResultSet = mysql_query("INSERT INTO messages(content, date, time, senderuserid, dialogid)
                          VALUES (
                              '" . mysql_real_escape_string($_POST['content']) . "',
                              '" . mysql_real_escape_string(f_Date($timeStamp)) . "',
                              '" . mysql_real_escape_string(f_Time($timeStamp)) . "',
                              '" . $_SESSION['id'] . "',
                              '" . mysql_real_escape_string($_POST['did']) . "')") or die(mysql_error());

$lastInsertId = mysql_insert_id();

$dialogUpdateResultSet = mysql_query("UPDATE dialogs SET
                                                          getteruserid = if(getteruserid = '" . $_SESSION['id'] . "', senderuserid, getteruserid),
                                                          senderuserid = '" . $_SESSION['id'] . "'

                                      WHERE
                                            id = '" . $_POST['did'] . "'") or die(mysql_error());

if ($msgInsertResultSet && $dialogUpdateResultSet) {
    commitTransaction();
} else {
    rollbackTransaction();
}

redirect($_SERVER['HTTP_REFERER']);


?>